package com.example.revise.ui.gallery

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.revise.R
import com.example.revise.data.VideoItem
import com.example.revise.databinding.FragmentGalleryBinding
import com.example.revise.ui.home.HomeFragment

class GalleryFragment : Fragment() {

    private var _binding: FragmentGalleryBinding? = null
    private val binding get() = _binding!!

    private fun getCategoryDisplayName(category: String): String {
        return when (category) {
            "number" -> "数量关系"
            "data" -> "资料分析"
            "word" -> "言语理解"
            "politics" -> "政治理论"
            "common" -> "常识"
            "judge" -> "判断推理"
            "plat" -> "平面图推"
            "dimen" -> "空间重构"
            else -> category
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentGalleryBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Group videos by category
        val galleryItems = mutableListOf<GalleryItem>()
        HomeFragment.videos.groupBy { 
            context?.resources?.getResourceEntryName(it.videoResId)?.split("_")?.first() ?: ""
        }.forEach { (category, categoryVideos) ->
            if (category.isNotEmpty()) {
                galleryItems.add(GalleryItem.Header(getCategoryDisplayName(category)))
                galleryItems.addAll(categoryVideos.map { GalleryItem.Video(it) })
            }
        }

        // Create a custom GridLayoutManager that handles full-width headers
        val gridLayoutManager = GridLayoutManager(context, 2).apply {
            spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return when (galleryItems[position]) {
                        is GalleryItem.Header -> 2 // Full width for headers
                        is GalleryItem.Video -> 1  // Half width for videos
                    }
                }
            }
        }

        // Set up RecyclerView
        binding.galleryRecyclerView.apply {
            layoutManager = gridLayoutManager
            adapter = GalleryAdapter(galleryItems)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}